import { Component, OnInit, Input } from '@angular/core';
import { UploadFile, UploadFilter, NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ApiService } from 'src/app/core/service/api.service';

@Component({
  selector: 'app-upload-war',
  templateUrl: './upload-war.component.html',
  styleUrls: ['./upload-war.component.scss']
})
export class UploadWarComponent implements OnInit {
  @Input() appUuid: string;
  uploadWar: FormGroup;
  uploading = false;

  fileList: UploadFile[] = [];    // 文件列表
  filters: UploadFilter[] = [{    // 过滤文件
    name: 'type',
    fn: (fileList: UploadFile[]) => {
      this.filter(fileList);
      return fileList;
    }
  }];

  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private apiService: ApiService,
    fb: FormBuilder
  ) {
    this.uploadWar = fb.group({
      uploadFile: ['', Validators.compose([Validators.required])]
    });
  }

  filter(fileList: UploadFile[]): any {
    // tslint:disable-next-line:no-bitwise
    const filterFiles = fileList.filter(w => ~['war'].indexOf(w.name.substring(w.name.length - 3, w.name.length)));
    if (filterFiles.length !== filterFiles.length) {
      this.message.error(`包含文件格式不正确，只支持 war 格式`);
      return filterFiles;
    }
  }

  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  }

  handleUpload(): void {
    const formData = new FormData();
    formData.append('appUuid', this.appUuid);
    this.fileList.forEach((file: any) => {
      formData.append('file', file);
    });
    this.uploading = true;
    this.fileUpload('/data/application/uploadwar', formData);
  }

  fileUpload(path: string, formData: FormData) {
    this.apiService.fileUpLoad(path, formData).subscribe((uploadResult) => {
      if (uploadResult.status === 1) {
        this.message.success('上传成功!', {
          nzDuration: 10000
        });
        this.uploading = false;
        this.modal.destroy();
      }
      if (uploadResult.status === 0) {
        this.message.error('上传失败!', {
          nzDuration: 10000
        });
        this.uploading = false;
      }
    });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

  ngOnInit() { }

}
